﻿using AutoMapper;
using BaseData.API.Write.Applications.Commands;
using BaseData.Domain;
using BaseData.ErrorCode;
using BaseData.Infrastructure.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace BaseData.API.Write.Applications.CommandHandlers
{
    /// <summary>
    /// 添加角色--配置权限 命令
    /// </summary>
    public class AddRoleCommandHandler : IRequestHandler<AddRoleCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Role> roleRep;
        private readonly IBaseRepository<RolePermissionRelation> rolePermissionRep;
        private readonly IBaseRepository<Permission> permissionRep;
        private readonly IMapper mapper;
        private readonly ILogger<AddRoleCommandHandler> logger;

        public AddRoleCommandHandler(IBaseRepository<Role> roleRep,
            IBaseRepository<RolePermissionRelation> rolePermissionRep,
            IBaseRepository<Permission> permissionRep,
            IMapper mapper,
            ILogger<AddRoleCommandHandler> logger)
        {
            this.roleRep = roleRep;
            this.rolePermissionRep = rolePermissionRep;
            this.permissionRep = permissionRep;
            this.mapper = mapper;
            this.logger = logger;
        }
        public async Task<ApiResult<int>> Handle(AddRoleCommand request, CancellationToken cancellationToken)
        {
            var count = await roleRep.GetAll().CountAsync(x => x.RoleName == request.RoleName);
            if (count > 0)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnum.添加失败,
                    Message = "该角色已存在!!!",
                    Data = -1
                };
            }

            ApiResult<int> result = new ApiResult<int>();
            result.Code = ApiEnum.添加成功;
            result.Message = ApiEnum.添加成功.ToString();

            // 1. 获取 EF Core 执行策略（自动兼容重试与事务）
            var executionStrategy = roleRep.DB.Database.CreateExecutionStrategy();
            return await executionStrategy.ExecuteAsync(async () =>
            {
                using (var tran = await roleRep.DB.Database.BeginTransactionAsync(cancellationToken))
                {
                    try
                    {
                        //添加角色表
                        var roles = mapper.Map<Role>(request);
                        roles.CreateTime = DateTime.Now;
                        await roleRep.AddAsync(roles);
                        var list = new List<RolePermissionRelation>();
                        foreach (var item in request.PermissionIds)
                        {
                            list.Add(new RolePermissionRelation
                            {
                                RoleId = roles.RoleId,
                                PermissionId = item
                            });
                        }
                        await rolePermissionRep.AddRange(list);
                        //提交
                        tran.Commit();
                    }
                    catch (Exception ex)
                    {
                        logger.LogError("=>" + ex.Message);
                        result.Code = ApiEnum.添加失败;
                        result.Message = ApiEnum.添加失败.ToString() + ex.Message;
                        tran.Rollback();
                    }
                }
                return result;
            });

           

            
        }
    }
}
